﻿using MiniExcelLibs;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RecordBill.Dtos;
using RecordBill.Extensions;
using System.IO;

namespace RecordBill.Core
{
   public  class DataImport
    {

        static DataImport()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        }
    
        public static UIBillStatisticsInfo ImportFile(string filePath)
        {
            UIBillStatisticsInfo billInfo = new UIBillStatisticsInfo();
            // 注意：useHeaderRow = false，这样列名为 Column1, Column2, ...
            var rows = MiniExcel.Query(filePath, useHeaderRow: false).ToList();

            // 第3行（索引2）
            if (rows.Count < 3)
                throw new Exception("文件太短");

            string thirdRowText = rows[2].A?.ToString() ?? "";

            var startMatch = System.Text.RegularExpressions.Regex.Match(thirdRowText, @"起始时间：\[(.*?)\]");
            var endMatch = System.Text.RegularExpressions.Regex.Match(thirdRowText, @"终止时间：\[(.*?)\]");

            if (!startMatch.Success || !endMatch.Success)
                throw new Exception("无法解析时间范围");

            DateTime startTime = DateTime.ParseExact(startMatch.Groups[1].Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
            DateTime endTime = DateTime.ParseExact(endMatch.Groups[1].Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

            Console.WriteLine($"起始时间: {startTime}");
            Console.WriteLine($"终止时间: {endTime}");
            billInfo.BillStartTime = startTime;
            billInfo.BillEndTime = endTime;
            // 查找标题行
            int headerIndex = -1;
            for (int i = 0; i < rows.Count; i++)
            {
                string col1 = rows[i].A?.ToString() ?? "";
                string col2 = rows[i].B?.ToString() ?? "";
                if (col1.Contains("交易时间") && col2.Contains("交易类型"))
                {
                    headerIndex = i;
                    break;
                }
            }

            if (headerIndex == -1)
                throw new Exception("未找到交易明细标题行");

            // 读取交易数据
            var transactions = new List<Transaction>();
            for (int i = headerIndex + 1; i < rows.Count; i++)
            {
                var row = rows[i];
                string tradeTimeStr = row.A?.ToString();
                if (string.IsNullOrWhiteSpace(tradeTimeStr))
                    break;

                var trans = new Transaction
                {
                    TradeTime = DateTime.Parse(tradeTimeStr),
                    TradeType = (row.B?.ToString() ?? "").Trim(),
                    Counterparty = (row.C?.ToString() ?? "").Trim(),
                    Goods = (row.D?.ToString() ?? "").Trim(),
                    IncomeOrExpense = (row.E?.ToString() ?? "").Trim(),
                    Amount = ParseAmount(row.F?.ToString()),
                    PaymentMethod = (row.G?.ToString() ?? "").Trim(),
                    Status = (row.H?.ToString() ?? "").Trim(),
                    TransactionId = (row.I?.ToString() ?? "").Trim(),
                    MerchantOrderId = (row.J?.ToString() ?? "").Trim(),
                    Remark = (row.K?.ToString() ?? "").Trim()
                };
                var typeKey = PrismManager.GetBillTypeKey(trans.Counterparty);
                trans.StatisticsType = typeKey;
                transactions.Add(trans);
            }
            billInfo.BillItemList = transactions;
            return billInfo;
        }
        // === 工具方法 ===
        static decimal ParseAmount(string input)
        {
            if (string.IsNullOrWhiteSpace(input)) return 0m;
            var clean = System.Text.RegularExpressions.Regex.Replace(input, @"[^\d.,-]", "");
            clean = clean.Replace(",", "");
            return decimal.TryParse(clean, NumberStyles.Float, CultureInfo.InvariantCulture, out var val) ? val : 0m;
        }

        public static List<CashbookRecord> ParseCashbookRecordsSkipHeader(string filePath)
        {
            try
            {
                // 读取所有行
                var lines = File.ReadAllLines(filePath,Encoding.GetEncoding("GB2312"));

                // 找到数据开始的行（包含"记录时间"的行）
                int dataStartIndex = -1;
                for (int i = 0; i < lines.Length; i++)
                {
                    if (lines[i].StartsWith("记录时间"))
                    {
                        dataStartIndex = i;
                        break;
                    }
                }

                if (dataStartIndex == -1)
                    return new List<CashbookRecord>();

                // 创建临时CSV内容
                var csvContent = string.Join(Environment.NewLine, lines.Skip(dataStartIndex));

                return ParseCashbookRecordsFromContent(csvContent);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"解析CSV文件时出错: {ex.Message}");
                return new List<CashbookRecord>();
            }
        }

        // 如果要从文件内容字符串解析（而不是文件路径）
        private static List<CashbookRecord> ParseCashbookRecordsFromContent(string csvContent)
        {
            try
            {
                // 将CSV内容写入内存流
                using var stream = new MemoryStream();
                using var writer = new StreamWriter(stream);
                writer.Write(csvContent);
                writer.Flush();
                stream.Position = 0;

                // 从内存流读取
                var records = MiniExcel.Query<CashbookRecord>(stream, excelType: ExcelType.CSV);

                return records.ToList();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"解析CSV内容时出错: {ex.Message}");
                return new List<CashbookRecord>();
            }
        }
    }
}
